<?php

namespace app\videos\server;

use app\common\server\Service;
use app\videos\model\Videos as VideosModel;
use app\videos\model\VideoParse as VideoParseModel;
use app\user\model\User as UserModel;
use app\videos\model\VideosDanmu as VideosDanmuModel;
use app\videos\model\VideosType as VideosTypeModel;
use app\videos\validate\VideosDanmu as VideosDanmuValidate;
use app\user\model\UserLike as UserLikeModel;
use one\Http;
use think\Db;

class Videos extends Service
{

    public function initialize()
    {
        parent::initialize();
        if (!isset($this->serviceKey) || empty($this->serviceKey) || cache('serviceKey') != $this->serviceKey) {
            exit(json_encode(['msg' => '非法操作！', 'code' => 712]));
        }
        $this->VideosModel = new VideosModel();
        $this->VideoParseModel = new VideoParseModel();
        $this->UserModel = new UserModel();
        $this->VideosTypeModel = new VideosTypeModel();
        $this->VideosDanmuModel = new VideosDanmuModel();
        $this->VideosDanmuValidate = new VideosDanmuValidate();
        $this->UserLikeModel = new UserLikeModel();
    }
    /**
     * 用户添加喜欢视频
     *
     * @param [type] $data
     * @param [type] $user
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function addLike($data, $user)
    {
        if (!isset($user['id']) || !$user['id']) {
            $this->error = "请先登录";
            return false;
        }
        if ($this->UserLikeModel->where('uid', $user['id'])->find()) {
            $map = [];
            $map[] = ['uid', 'eq', $user['id']];
            $map[] = ['vid', 'like', "%{$data["id"]}%"];
            if (!$this->UserLikeModel->where($map)->find()) {
                $sql = "UPDATE hisi_user_like SET vid=concat(',{$data['id']}',vid) WHERE uid={$user['id']}";
                Db::execute($sql);
                $msg = "收藏成功";
            } else {
                $sql = "UPDATE hisi_user_like SET vid = replace(vid, ',{$data['id']}', '') WHERE uid={$user['id']}";
                Db::execute($sql);
                $msg = "取消收藏";
            }
        } else {
            $this->UserLikeModel->save(['uid' => $user['id'], 'vid' => ",{$data['id']}"]);
        }
        $this->error = $msg;
        return true;
    }

    /**
     * 获取视频列表
     *
     * @param [type] $data
     * @param [type] $user
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function getVideoLists($data, $user)
    {
        $page = $data['page'];
        $limit = $data['limit'];
        $map = [];
        $map[] = ['vod_status', 'eq', 1];
        $map[] = ['vod_lock', 'eq', 0];
        // 一级分类 电影电视剧动漫

        if ($data['type_id_1'] == '全部' && $data['area'] == '全部' && $data['year'] == '全部') {
            // var_dump($data['type_id']);
            $map[] = ['type_id|type_id_1', 'eq', $data['type_id']];
        } else

        if ($data['type_id_1'] != '全部' && $data['area'] != '全部' && $data['year'] != '全部') {
            $map[] = ['type_id_1', 'eq', $data['type_id']];
            $map[] = ['type_id', 'eq', $data['type_id_1']];
            $map[] = ['vod_area', 'like', "%{$data['area']}%"];
            $map[] = ['vod_year', 'like', "%{$data['year']}%"];
        } else

        if ($data['type_id_1'] == '全部' && $data['area'] != '全部' && $data['year'] == '全部') {
            $map[] = ['type_id|type_id_1', 'eq', $data['type_id']];
            $map[] = ['vod_area', 'like', "%{$data['area']}%"];
        } else

        if ($data['type_id_1'] == '全部' && $data['area'] == '全部' && $data['year'] != '全部') {
            $map[] = ['type_id|type_id_1', 'eq', $data['type_id']];
            $map[] = ['vod_year', 'like', "%{$data['year']}%"];
        } else

        if ($data['type_id_1'] != '全部' && $data['area'] != '全部' && $data['year'] == '全部') {
            $map[] = ['type_id_1', 'eq', $data['type_id']];
            $map[] = ['type_id', 'eq', $data['type_id_1']];
            $map[] = ['vod_area', 'like', "%{$data['area']}%"];
        } else

        if ($data['type_id_1'] != '全部' && $data['area'] == '全部' && $data['year'] == '全部') {
            $map[] = ['type_id_1', 'eq', $data['type_id']];
            $map[] = ['type_id', 'eq', $data['type_id_1']];
        } else

        if ($data['type_id_1'] == '全部' && $data['area'] != '全部' && $data['year'] != '全部') {
            $map[] = ['type_id|type_id_1', 'eq', $data['type_id']];
            $map[] = ['vod_area', 'like', "%{$data['area']}%"];
            $map[] = ['vod_year', 'like', "%{$data['year']}%"];
        } else 
        
        if ($data['type_id_1'] != '全部' && $data['area'] == '全部' && $data['year'] != '全部') {
            $map[] = ['type_id_1', 'eq', $data['type_id']];
            $map[] = ['type_id', 'eq', $data['type_id_1']];
            $map[] = ['vod_year', 'like', "%{$data['year']}%"];
        }

        // 会员控制
        $map['user'] = $user;
        return $this->VideosModel->getList($map, $page, $limit, 'vod_level desc, vod_time desc'); 
    }
    /**
     * 获取视频分类
     *
     * @param [type] $data
     * @param [type] $user
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function getVideoTypeLists($data, $user)
    {
        $list = $this->VideosTypeModel->listToTree('_c', ($user && $user['group_id'] == 6));
        if (empty($list)) {
            $this->error = "获取失败";
            return false;
        }
        return $list;
    }

    public function getVideoArea($data, $user)
    {
        // $list = $this->VideosModel->getVideoFieldGroup('vod_area');
        // if (empty($list)) {
        //     $this->error = "获取失败";
        //     return false;
        // }
        // foreach ($list as $key => $value) {
        //     if (empty($value['vod_area'])) {
        //         unset($list[$key]);
        //     }
        // }
        // arrayMsort($list, 'vod_area');
        // array_splice($list, 0, 3);
        // array_unshift($list, ['vod_area' => '全部']);
        // return array_values($list);
        $list = [
            ['vod_area' => '全部'],
            ['vod_area' => '大陆'],
            ['vod_area' => '中国香港'],
            ['vod_area' => '美国'],
            ['vod_area' => '欧洲'],
            ['vod_area' => '韩国'],
            ['vod_area' => '日本'],
            ['vod_area' => '泰国'],
            ['vod_area' => '印度'],
            ['vod_area' => '其他'],
        ];
        return $list;
    }

    public function getVideoClass($data, $user)
    {
        $list = $this->VideosModel->getVideoFieldGroup('vod_class');
        if (empty($list)) {
            $this->error = "获取失败";
            return false;
        }
        foreach ($list as $key => $value) {
            if (empty($value['vod_class'])) {
                unset($list[$key]);
            }
            if (false !== stripos($value['vod_class'], '伦理')) {
                unset($list[$key]);
            }
            if (false !== stripos($value['vod_class'], '福利')) {
                unset($list[$key]);
            }
        }
        arrayMsort($list, 'vod_class');
        array_unshift($list, ['vod_class' => '全部']);
        return array_values($list);
    }

    public function getVideoYear($data, $user)
    {
        $list = $this->VideosModel->getVideoFieldGroup('vod_year');
        if (empty($list)) {
            $this->error = "获取失败";
            return false;
        }
        foreach ($list as $key => $value) {
            if (empty($value['vod_year']) || $value['vod_year'] > date("Y", time())) {
                unset($list[$key]);
            }
        }
        $vod_year = array_column($list, 'vod_year');
        array_multisort($vod_year, SORT_DESC, $list);
        array_unshift($list, ['vod_year' => '全部']);
        return array_values($list);
    }

    public function getVideoDetail($data, $user)
    {
        $info = $this->VideosModel->getVideoDetail($data['vid']);
        if (empty($info)) {
            $this->error = "获取失败";
            return false;
        }

        if ($info['vod_lock'] == 1) {
            $this->error = "因版权限制已下架";
            return false;
        }

        if (empty($info['vod_play_url'])) {
            $this->error = "未找到信息，请反馈给管理员";
            return false;
        }
        // 切割后台配置播放源
        $source = config('video.source_name');
        $source = array_filter(explode("\n", $source));
        foreach ($source as $k => $v) {
            $tmp = explode(':', str_replace('：', ':', $v));
            $source_arr[$tmp[0]] = $tmp[1];
        }
        $error = [];
        // 线路列表结束
        $arr['vod_play_from'] = explode('$$$', $info['vod_play_from']);
        foreach ($arr['vod_play_from'] as $k => $v) {
            if (isset($source_arr[$v])) {
                $arr['vod_play_from'][$k] = $source_arr[$v];
            } else {
                array_push($error, $arr['vod_play_from'][$k]);
                unset($arr['vod_play_from'][$k]);
            }
        }
        // 重新排序开始
        $tmp = [];
        $old_vod_play_from = $arr['vod_play_from'];
        $arr['vod_play_from'] = [];
        $source_arr = array_values($source_arr);
        foreach ($source_arr as $key => $val) {
            if (($idx = array_search($val, $old_vod_play_from)) !== FALSE) {
                $tmp[$key]['val'] = $val;
                $tmp[$key]['idx'] = $idx;
                $arr['vod_play_from'][] = $val;
            }
        }
        $new_vod_play_from = array_values($tmp);
        $source_arr = null;
        $tmp = null;
        // 排序结束
        if (count($error) > 0 && count($arr['vod_play_from']) <= 0) {
            $this->error = '缺少播放线路，须在 系统-系统配置-视频配置内添加播放器代码：' . implode($error);
            return false;
        }

        $srcList = explode('$$$', $info['vod_play_url']);
        $tmp = [];
        foreach ($new_vod_play_from as $i => $m) {
            // 是否多个
            if (strstr($srcList[$m['idx']], '#')) {
                $juji = explode('#', $srcList[$m['idx']]);
                foreach ($juji as $ke => $val) {
                    if (!empty($val)) {
                        $dizhi = explode('$', $val);
                        if (!empty($dizhi) && isset($dizhi[0]) && isset($dizhi[1])) {
                            $arr['srcList'][$m['val']][$ke]['name'] = $dizhi[0];
                            $arr['srcList'][$m['val']][$ke]['url'] = $dizhi[1];
                        }
                    }
                }
            } else {
                $dizhi = explode('$', $srcList[$m['idx']]);
                if (!empty($dizhi) && isset($dizhi[0]) && isset($dizhi[1])) {
                    $arr['srcList'][$m['val']][$k]['name'] = $dizhi[0];
                    $arr['srcList'][$m['val']][$k]['url'] = $dizhi[1];
                    $arr['srcList'][$m['val']] = array_values($arr['srcList'][$m['val']]);
                }
            }
        }

        $arr['vid'] = $info['vod_id'];
        $arr['title'] = $info['vod_name'];
        $arr['vod_pic'] = $info['vod_pic'];
        $arr['remark'] = strip_tags($info['vod_content']);
        $arr['type'] = $info['type_id_1'];
        $arr['vod_score'] = $info['vod_score'];
        $arr['vod_time'] = $info['vod_time'];
        $arr['vod_actor'] = $info['vod_actor'];
        $arr['vod_year'] = $info['vod_year'];
        // $arr['count'] = count($arr['srcList']);
        // $arr['recommend'] = $this->getRecommendVideo($info['type_id']);
        // $arr['recommend'] = [];
        
        if (isset($data['app']) && $data['app'] == 1) {
            $arr['danmuList'] = $this->getDanmuList(['vid' => $info['vod_id'], 'index' => isset($data['index']) ? $data['index'] : 0], $user);
        }
        
        // $arr['danmuList'] = [];
        // $arr['downLoadList'] = [];
        // if ($info['vod_down_url']) {
        //     $downLoadList = explode('#', $info['vod_down_url']);
        //     foreach ($downLoadList as $key => $value) {
        //         $tmp = explode('$', $value);
        //         $arr['downLoadList'][$key]['lable'] = $tmp[0];
        //         $arr['downLoadList'][$key]['value'] = $tmp[1];
        //     }
        // }
        // $isLike = false;
        // if (isset($user['id']) && !empty($user['id'])) {
        //     // 是否收藏
        //     $map = [];
        //     $map[] = ['uid', 'eq', $user['id']];
        //     $map[] = ['vid', 'like', "%{$data["vid"]}%"];
        //     $isLike = $this->UserLikeModel->where($map)->find();
        // }
        // $arr['isLike'] = $isLike ? true : false;
        return $arr;
    }
    // 推荐电影
    public function getRecommendVideo($type = 1)
    {
        $map = [];
        $map[] = ['vod_status', 'eq', 1];
        $map[] = ['type_id', 'eq', $type];
        $list = $this->VideosModel->getList($map, 1, 3, 'vod_score desc, rand()');
        return $list['list'];
    }
    /**
     * 弹幕列表
     *
     * @param [type] $data
     * @param [type] $user
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function getDanmuList($data, $user)
    {
        $map = [];
        if ((int)$data['vid'] == 0) {
            $info = $this->VideosModel->getVideoDetail($data['vid']);
            if (empty($info)) {
                $this->error = "获取失败";
                return false;
            }
            $map[] = ['vid', 'eq', $info['vod_id']];
        } else {
            $map[] = ['vid', 'eq', $data['vid']];
        }
        $map[] = ['index', 'eq', $data['index']];
        $list = $this->VideosDanmuModel->getList($map, 0);
        $danmuList = [];
        foreach ($list['list'] as $key => $value) {
            $danmuList[$key]['text'] = $value['text'];
            $danmuList[$key]['color'] = $value['color'];
            $danmuList[$key]['time'] = $value['time'];
        }
        return array_values($danmuList);
    }
    /**
     * 搜索
     *
     * @param [type] $data
     * @param [type] $user
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function searchKeywords($data, $user)
    {
        $keyword = trim($data['keyword']);
        // 分词
        // $str_arr = getStrSplit($keyword, 0.6);
        $map['sql'] = "(instr(vod_name, '{$keyword}')>0 or instr(vod_sub, '{$keyword}')>0) and vod_status = 1";
        // $map[] = ['vod_name|vod_director|vod_tag|vod_sub', 'like', "%$keyword%"];
        // $map[] = ['vod_status', 'eq', 1];
        // $map = "vod_name like '%$keyword%' or vod_director like '%$keyword%' and vod_status = 1";
        // 会员控制
        $map['user'] = $user;

        $order = 'vod_level desc, vod_time desc, vod_year desc';
        $fields = 'vod_id, type_id, vod_name, vod_actor, vod_class, vod_area, vod_lang, vod_pic, vod_tag, vod_status, vod_year, vod_hits, vod_level, vod_time';

        return $this->VideosModel->getList($map, $data['page'], isset($data['limit']) ? $data['limit'] : 10, $order, $fields);
    }
    /**
     * 首页推荐电影和电视剧
     *
     * @param [type] $data
     * @param [type] $user
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function getHomeVideoLists($data, $user)
    {
        $order = 'vod_level desc, vod_year desc, vod_hits desc';
        $fields = 'vod_id, vod_name, vod_pic, vod_play_url, vod_remarks, vod_score';
        // 推荐热门 ，年份倒序，点击倒序
        $map = [];
        $map[] = ['vod_status', 'eq', 1];
        $map[] = ['vod_lock', 'eq', 0];
        $map['user'] = $user;
        $list['recommend'] = $this->VideosModel->getList($map, 1, 18, $order, $fields);
        // $list['recommend'] = $this->VideosModel->getRandList('vod_status=1 AND vod_lock=0', 't1.vod_level desc, t1.vod_year desc, t1.vod_hits desc', 't1');
        // 推荐电影 ，年份倒序，点击倒序
        $map = [];
        $map[] = ['vod_status', 'eq', 1];
        $map[] = ['vod_lock', 'eq', 0];
        $map[] = ['type_id_1|type_id', 'eq', config('video.movie_id') ?: 1];
        $map['user'] = $user;
        $list['movie'] = $this->VideosModel->getList($map, 1, 9, $order, $fields);
        // 推荐电视剧 ，年份倒序，点击倒序
        $map = [];
        $map[] = ['vod_status', 'eq', 1];
        $map[] = ['vod_lock', 'eq', 0];
        $map[] = ['type_id_1|type_id', 'eq', config('video.tv_id') ?: 2];
        $map['user'] = $user;
        $list['tv'] = $this->VideosModel->getList($map, 1, 9, $order, $fields);
        // 动漫
        $map = [];
        $map[] = ['vod_status', 'eq', 1];
        $map[] = ['vod_lock', 'eq', 0];
        $map[] = ['type_id_1|type_id', 'eq', config('video.acg_id') ?: 4];
        $map['user'] = $user;
        $list['acg'] = $this->VideosModel->getList($map, 1, 9, $order, $fields);
        // 推荐综艺
        $map = [];
        $map[] = ['vod_status', 'eq', 1];
        $map[] = ['vod_lock', 'eq', 0];
        $map[] = ['type_id_1|type_id', 'eq', config('video.variety_id') ?: 3];
        $map['user'] = $user;
        $list['variety'] = $this->VideosModel->getList($map, 1, 9, $order, $fields);
        return $list;
    }

    /**
     * 热词
     *
     * @param [type] $data
     * @param [type] $user
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function hotKeyWords($data, $user)
    {
        $map = [];
        $map[] = ['vod_status', 'eq', 1];
        $fields = 'vod_id, vod_name';
        return $this->VideosModel->getList($map, $data['page'], $data['limit'], 'vod_level desc, vod_year desc, vod_hits desc', $fields);
    }

    public function getTypeVideoLists($data, $user)
    {
        $type = isset($data['type']) ? $data['type'] : '';
        $page = isset($data['page']) ? $data['page'] : 1;
        $limit = isset($data['limit']) ? $data['limit'] : 7;
        $map = [];
        $map[] = ['vod_status', 'eq', 1];
        $map[] = ['vod_lock', 'eq', 0];
        switch ($type) {
            case '1':
                $map[] = ['type_id_1|type_id', 'eq', 1];
                break;
            case '2':
                $map[] = ['type_id_1|type_id', 'eq', 2];
                break;
            case '3':
                $map[] = ['type_id_1|type_id', 'eq', 4];
                break;
            case '4':
                $map[] = ['type_id_1|type_id', 'eq', 3];
                break;
            default:
                $map[] = ['type_id_1|type_id', 'eq', 1];
                break;
        }
        return $this->VideosModel->getList($map, $page, $limit, 'vod_level desc, vod_time desc, vod_hits desc');
    }


    /**
     * 搜索tab推荐
     */
    public function searchTabs($data, $user)
    {
        $map = [];
        $map[] = ['vod_status', 'eq', 1];
        switch ($data['type']) {
            case 1:
                $order = 'vod_level desc'; // 根据 推荐值 倒序排序，需手动在cms后台设置视频推荐等级
                break;
            case 2:
                $map[] = ['type_id_1', 'eq', 1]; // 电影类目id
                $order = 'vod_level desc, vod_time desc, vod_hits desc'; // 自动根据推荐值、入库时间、电影上映年份、点击量倒序排序
                break;
            case 3:
                $map[] = ['type_id_1', 'eq', 2]; // 电视剧类目id
                $order = 'vod_level desc, vod_time desc, vod_hits desc'; // 自动根据推荐值、入库时间、电影上映年份、点击量倒序排序
                break;
            default:
                $order = 'vod_level desc'; // 根据 推荐值 倒序排序，需手动在cms后台设置视频推荐等级
                break;
        }
        return $this->VideosModel->searchTabs($map, $order);
    }


    public function getRecommendList($data, $user)
    {
        $order = 'vod_level desc, vod_year desc, vod_hits desc';
        $fields = 'vod_id, vod_name, vod_pic, vod_remarks';
        $map = [];
        $map[] = ['vod_status', 'eq', 1];
        $map[] = ['vod_lock', 'eq', 0];
        $map['user'] = $user;

        $page =  isset($data['page']) ? $data['page'] : 1;
        $limit =  isset($data['limit']) ? $data['limit'] : 9;
        $list = $this->VideosModel->getList($map, $page, $limit, $order, $fields);
        return $list;
    }
    public function getMoviesList($data, $user)
    {
        $tid = config('video.movie_id') ?: 1;
        $order = 'vod_level desc, vod_year desc, vod_hits desc';
        $map = [];
        $map[] = ['vod_status', 'eq', 1];
        $map[] = ['vod_lock', 'eq', 0];
        $map[] = ['type_id_1|type_id', 'eq', $tid];
        return $this->VideosModel->getRandByPage($map, 9, $order);
    }
    public function getTvViedeosList($data, $user)
    {
        $tid = config('video.tv_id') ?: 2;
        $order = 'vod_level desc, vod_year desc, vod_hits desc';
        $map = [];
        $map[] = ['vod_status', 'eq', 1];
        $map[] = ['vod_lock', 'eq', 0];
        $map[] = ['type_id_1|type_id', 'eq', $tid];
        return $this->VideosModel->getRandByPage($map, 9, $order);
    }
    public function getAcgViedeosList($data, $user)
    {
        $tid = config('video.acg_id') ?: 4;
        $order = 'vod_level desc, vod_year desc, vod_hits desc';
        $map = [];
        $map[] = ['vod_status', 'eq', 1];
        $map[] = ['vod_lock', 'eq', 0];
        $map[] = ['type_id_1|type_id', 'eq', $tid];
        return $this->VideosModel->getRandByPage($map, 9, $order);
    }
    public function getVarietyViedeosList($data, $user)
    {
        $tid = config('video.variety_id') ?: 3;
        $order = 'vod_level desc, vod_year desc, vod_hits desc';
        $map = [];
        $map[] = ['vod_status', 'eq', 1];
        $map[] = ['vod_lock', 'eq', 0];
        $map[] = ['type_id_1|type_id', 'eq', $tid];
        return $this->VideosModel->getRandByPage($map, 9, $order);
    }
}
